
package com.segment.dcore.dubbo.filter.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;

import com.segment.dcore.base.constants.FilterOrderConstants;
import com.segment.dcore.base.filter.InvokeContext;
import com.segment.dcore.base.filter.ServiceFilter;
import com.segment.dcore.dubbo.filter.AbstractDubboServiceFilter;
import com.segment.dcore.dubbo.filter.context.DubboInvokeContext;

/**
 * 服务访问
 *
 * Created by huapeng.hhp on 2017/2/27.
 */
@Service("dubboServiceInvokeFilter")
public class DubboServiceInvokeFilter extends AbstractDubboServiceFilter {

	/** LOGGER for ServiceInvokeFilter */
	private static final Logger LOGGER = LoggerFactory.getLogger(DubboServiceInvokeFilter.class);

	/**
	 * @see ServiceFilter#getOrder()
	 * @return
	 */
	@Override
	public int getOrder() {
		return FilterOrderConstants.SERVICE_INVOKE_FILTER_ORDER;
	}

	@Override
	protected void before(InvokeContext invokeContext) {
		DubboInvokeContext realInvokeContext = (DubboInvokeContext) invokeContext;
		Invoker<?> invoke = realInvokeContext.getInvoker();
		Invocation inv = realInvokeContext.getInv();
		Result result = invoke.invoke(inv);
		if (result == null) {
			LOGGER.error("cannot return success result");
			realInvokeContext.setResult(null);
			return;
		}
		if (result.hasException()) {
			String invokeContextStr = com.alibaba.fastjson.JSON.toJSONString(invokeContext);
			LOGGER.error(invokeContextStr, result.getException());
			realInvokeContext.setResult(result);
			return;
		}
		realInvokeContext.setResult(result);
	}

	@Override
	protected void after(InvokeContext invokeContext) {
		return;
	}
}
